<script setup>
import { ref } from 'vue'
import avatar from '@/assets/default.png'
import { useUserInfoStore } from "@/stores/userinfo.js"
import { useTokenStore } from "@/stores/token.js"
import { userAvatarUpdate } from "@/api/user.js"
import { ElMessage } from "element-plus"

const userinfostore = useUserInfoStore()
const usertoken = useTokenStore()
const uploadRef = ref() // 确保el-upload组件绑定ref

// 用户头像地址
const imgUrl = ref(userinfostore.info.userPic)

// 上传成功回调
const uploadSuccess = (result) => {
  // 打印结果以确认数据结构
  console.log('上传结果:', result)
  imgUrl.value = result.res // 根据实际结构调整字段
}

// 更新头像
const updateAvatar = async () => {
  try {
    await userAvatarUpdate(imgUrl.value)
    ElMessage.success("头像更新成功")
    userinfostore.info.userPic = imgUrl.value
  } catch (error) {
    ElMessage.error("更新失败")
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>更换头像</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <!-- 添加 ref="uploadRef" -->
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :auto-upload="true"
            :show-file-list="false"
            action="/api/upload"
            name="file"
            :headers="{ 'Authorization': usertoken.token }"
            :on-success="uploadSuccess">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <img v-else :src="avatar" width="278" />
        </el-upload>
        <br />
        <el-button
            type="primary"
            :icon="Plus"
            size="large"
            @click="uploadRef.$el.querySelector('input').click()">
          选择图片
        </el-button>
        <el-button
            type="success"
            :icon="Upload"
            size="large"
            @click="updateAvatar">
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
